const fs = require('fs')
const exec = require('child_process').exec
const { join } = require('path')
let timer = null
function watch (path) {
  fs.watch(path, (ev, filename) => {
    console.log(ev, path, new Date())
    exec('npm run build', (err, stdout, stderr) => {
      if (err) {
        console.log('error:\n', stderr)
      } else {
        console.log(stdout)
      }
    })
  })
}
function findSync (path) {
  let files = fs.readdirSync(path)
  clearTimeout(timer)
  timer = setTimeout(() => {
    watch(path)
  }, 300)

  files.forEach((val, index) => {
    let fPath = join(path, val)
    let stats = fs.statSync(fPath)
    if (stats.isDirectory()) findSync(fPath)
  })
}
findSync('./public/es6')
